// Package encrypt
// @Link  https://github.com/bufanyun/hotgo
// @Copyright  Copyright (c) 2023 HotGo CLI
// @Author  Ms <133814250@qq.com>
// @License  https://github.com/bufanyun/hotgo/blob/master/LICENSE
package encrypt

import (
	"encoding/base64"
	"encoding/hex"
	"github.com/forgoer/openssl"
	"github.com/golang-module/dongle"
	"github.com/wumansgy/goEncrypt/aes"
)

// AesECBEncrypt 加密
func AesECBEncrypt(src, key []byte) (dst []byte, err error) {
	return openssl.AesECBEncrypt(src, key, openssl.PKCS7_PADDING)
}

// AesECBDecrypt 解密
func AesECBDecrypt(src, key []byte) (dst []byte, err error) {
	return openssl.AesECBDecrypt(src, key, openssl.PKCS7_PADDING)
}

// MustAesECBEncryptToString
// Return the encryption result directly. Panic error
func MustAesECBEncryptToString(bytCipher, key string) string {
	dst, err := AesECBEncrypt([]byte(bytCipher), []byte(key))
	if err != nil {
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(dst)
}

// MustAesECBDecryptToString
// Directly return decryption result, panic error
func MustAesECBDecryptToString(bytCipher, key string) string {
	dst, err := AesECBDecrypt([]byte(bytCipher), []byte(key))
	if err != nil {
		panic(err)
	}
	return string(dst)
}

var key = "5406f826522a4320bedabeb6278fd1e0"
var iv = "7a84b8e1e9d34f7c349341c451cc864c"

var aesSecretKey = []byte("tu3c5t81v3wt1o8j")
var ivAes = []byte("1c5t86wt1o8c5t8z")

func AesCbcEncryptBase64(data string) (cipherTextBase64 string, err error) {

	encryBytes, err := aes.AesCbcEncrypt([]byte(data), aesSecretKey, ivAes)
	return base64.StdEncoding.EncodeToString(encryBytes), err
}

func AesCbcDecryptByBase64(cipherTextBase64 string) (plainText []byte, err error) {
	plainTextBytes, err := base64.StdEncoding.DecodeString(cipherTextBase64)
	if err != nil {
		return []byte{}, err
	}
	return aes.AesCbcDecrypt(plainTextBytes, aesSecretKey, ivAes)
}

func GetAesCipher() *dongle.Cipher {
	k, _ := hex.DecodeString(key)
	i, _ := hex.DecodeString(iv)
	cipher := dongle.NewCipher()
	cipher.SetMode(dongle.CTR) // CBC、CFB、OFB、CTR、ECB
	cipher.SetPadding(dongle.PKCS7)
	cipher.SetKey(k) // key 长度必须是 16、24 或 32 字节
	cipher.SetIV(i)  // iv must be 16 bytes (ECB mode doesn't require setting iv)
	return cipher
}
